package com.wx.util;

import javax.servlet.http.HttpServletRequest;

import com.wx.service.ShortURLService;
import com.wx.service.impl.ShortURLServiceImpl;
import com.wx.service.impl.SpringContextHolder;

/**
 * 短地址工具类
 * @author dingyaming
 *
 */
public class ShortURLUtil {
	
	private static ShortURLService shortURLService;
	
	/**
	 * 二级目录
	 */
	private static final String mapping = "/t/";
	
	/**
	 * 生成短地址
	 * @param url 目标地址 "http://www.xxx.com"全路径 "/ccc/ccc"项目内路径
	 * @return {key} 短地址关键字
	 */
	public static String getShortURL(String url){
		if(null==shortURLService){
			shortURLService= SpringContextHolder.getBean(ShortURLServiceImpl.class);
		}
		return shortURLService.addShortURL(url);
	}
	
	/**
	 * 生成短地址
	 * @param basePath 项目根路径
	 * @param url 目标地址 "http://www.xxx.com"全路径 "/ccc/ccc"项目内路径
	 * @return 全地址
	 */
	public static String getShortURL(String basePath, String url){
		return basePath+mapping+getShortURL(url);
	}
	
	/**
	 * 生成短地址
	 * @param request HttpServletRequest
	 * @param url 目标地址 "http://www.xxx.com"全路径 "/ccc/ccc"项目内路径
	 * @return 全地址
	 */
	public static String getShortURL(HttpServletRequest request, String url){
		int port = request.getServerPort();
		String basePath = request.getScheme()+"://"+request.getServerName();
		if(port!=80){
			basePath=basePath+":"+port;
		}
		basePath += request.getContextPath();
		return basePath+mapping+getShortURL(url);
	}

	
	public void setShortURLService(ShortURLService shortURLService){
		ShortURLUtil.shortURLService = shortURLService;
	}
}
